library(tidyverse)
library(plotly)

Poverty

Is there an association between the percentage of people whose income is below the poverty line and the incidence rate 1) across neighborhoods in NYC and 2) across neighborhoods in each borough?

data_clean <- read.csv("data_final.csv")

Poverty across neighborhoods in NYC

Calculate the correlation between the poverty percentage and the incident rate.

correlation <- cor(data_clean$incident_rate_by_year_nta, data_clean$Percent_poverty, use = "complete.obs")
print(paste("Correlation coefficient: ", correlation))
## [1] "Correlation coefficient:  0.508408410575774"

When examining all of the neighborhoods in NYC, there is a moderate positive linear relationship between the percentage of people below the poverty line (Percent_poverty) and the incident rate by neighborhood (incident_rate_by_year_nta).(r = 0.508).

data_clean %>%
  plot_ly(x = ~Percent_poverty, y = ~incident_rate_by_year_nta, 
          color = ~NTA, colors = "viridis", 
          type = "scatter", mode = "markers",
          text = ~paste("Neighborhood: ", NTA, "<br>Borough: ", BORO, 
                        "<br>% Below Poverty Line: ", Percent_poverty, 
                        "<br>Incident Rate: ", incident_rate_by_year_nta)) %>%
  layout(title = "Percent Below the Poverty Line and Incident Rate in NYC",
         xaxis = list(title = 'Percentage of People Whose Income is Below the Poverty Line'),
         yaxis = list(title = 'Incident Rate'),
         legend = list(title = list(text = 'Neighborhood')))

This plot suggests that neighborhoods with higher poverty rates tend to have higher incident rates.

Poverty By Borough

# Assuming your main data frame is named 'data_clean'

# Filter data for Manhattan
manhattan_data <- data_clean %>%
  filter(neighbourhood_group == "Manhattan")

# Filter data for Brooklyn
brooklyn_data <- data_clean %>%
  filter(neighbourhood_group == "Brooklyn")

# Filter data for The Bronx
bronx_data <- data_clean %>%
  filter(neighbourhood_group == "Bronx")

# Filter data for Staten Island
staten_island_data <- data_clean %>%
  filter(neighbourhood_group == "Staten Island")

# Filter data for Queens
queens_data <- data_clean %>%
  filter(neighbourhood_group == "Queens")
# Function to compute and print correlation
compute_correlation <- function(data, borough_name) {
  correlation <- cor(
    data$incident_rate_by_year_nta,
    data$Percent_poverty,
    use = "complete.obs"
  )
  cat("Correlation coefficient for", borough_name, ":", correlation, "\n")
}

compute_correlation(manhattan_data, "Manhattan")
## Correlation coefficient for Manhattan : 0.3344739
compute_correlation(brooklyn_data, "Brooklyn")
## Correlation coefficient for Brooklyn : 0.5686026
compute_correlation(bronx_data, "Bronx")
## Correlation coefficient for Bronx : 0.4462688
compute_correlation(staten_island_data, "Staten Island")
## Correlation coefficient for Staten Island : 0.5575556
compute_correlation(queens_data, "Queens")
## Correlation coefficient for Queens : 0.2797095
  • Positive Correlation Across All Boroughs:
  • The correlation coefficients for all boroughs are positive, indicating that as the percentage of people below the poverty line increases, the incident rate also tends to increase.
  • Differences in Correlation Strength:
  • Brooklyn (0.5686) and Staten Island (0.5576) show the highest correlations, suggesting that the relationship between poverty and incident rate is stronger in these boroughs.
  • Manhattan (0.3345) and Queens (0.2797) show weaker correlations, indicating that the relationship between poverty and incident rate is less pronounced in these areas.
  • Bronx (0.4463) has a moderate correlation, which also points to a positive but not as strong relationship.

Manhattan

compute_correlation(manhattan_data, "Manhattan")
## Correlation coefficient for Manhattan : 0.3344739
# Function to create scatter plot with trend line
# Scatter plot for Manhattan
data_clean |> 
  filter(neighbourhood_group == "Manhattan") |> 
  plot_ly(data = _, x = ~Percent_poverty, y = ~incident_rate_by_year_nta, 
          color = ~NTA,
          colors = "viridis", 
          type = "scatter",
          mode = "markers",
          text = ~paste("Neighborhood: ", NTA, "<br>Borough: ", neighbourhood_group, 
                        "<br>% Below Poverty Line: ", Percent_poverty, 
                        "<br>Incident Rate: ", incident_rate_by_year_nta)) |> 
    layout(title = "Percent Below the Poverty Line and Incident Rate in Manhattan",
           xaxis = list(title = 'Percentage of People Whose Income is Below the Poverty Line'),
           yaxis = list(title = 'Incident Rate'),
           legend = list(title = list(text = 'Neighborhood')))

Some neighborhoods, like East Harlem (North), East Harlem (South), and Chinatown-Two Bridges, seem to have both higher poverty percentages and higher incident rates, suggesting a more direct connection between poverty and incidents.

Brooklyn

# Scatter plot for Brooklyn
data_clean |> 
  filter(neighbourhood_group == "Brooklyn") |> 
  plot_ly(data = _, x = ~Percent_poverty, y = ~incident_rate_by_year_nta, 
          color = ~NTA,
          colors = "plasma", 
          type = "scatter",
          mode = "markers",
          text = ~paste("Neighborhood: ", NTA, "<br>Borough: ", neighbourhood_group, 
                        "<br>% Below Poverty Line: ", Percent_poverty, 
                        "<br>Incident Rate: ", incident_rate_by_year_nta)) |> 
    layout(title = "Percent Below the Poverty Line and Incident Rate in Brooklyn",
           xaxis = list(title = 'Percentage of People Whose Income is Below the Poverty Line'),
           yaxis = list(title = 'Incident Rate'),
           legend = list(title = list(text = 'Neighborhood')))

Brownsville, which has a high poverty rate (between 30-50%), also has some of the highest incident rates in Brooklyn, indicating that poverty may significantly impact incident rates in this neighborhood.

The Bronx

# Scatter plot for The Bronx
data_clean |> 
  filter(neighbourhood_group == "Bronx") |> 
  plot_ly(data = _, x = ~Percent_poverty, y = ~incident_rate_by_year_nta, 
          color = ~NTA,
          colors = "magma", 
          type = "scatter",
          mode = "markers",
          text = ~paste("Neighborhood: ", NTA, "<br>Borough: ", neighbourhood_group, 
                        "<br>% Below Poverty Line: ", Percent_poverty, 
                        "<br>Incident Rate: ", incident_rate_by_year_nta)) |> 
    layout(title = "Percent Below the Poverty Line and Incident Rate in The Bronx",
           xaxis = list(title = 'Percentage of People Whose Income is Below the Poverty Line'),
           yaxis = list(title = 'Incident Rate'),
           legend = list(title = list(text = 'Neighborhood')))

Claremont Village-Claremont (East) and Fordham Heights seem to have higher incident rates compared to other neighborhoods with similar poverty levels

Queens

# Scatter plot for Queens
data_clean |> 
  filter(neighbourhood_group == "Queens") |> 
  plot_ly(data = _, x = ~Percent_poverty, y = ~incident_rate_by_year_nta, 
          color = ~NTA,
          colors = "inferno", 
          type = "scatter",
          mode = "markers",
          text = ~paste("Neighborhood: ", NTA, "<br>Borough: ", neighbourhood_group, 
                        "<br>% Below Poverty Line: ", Percent_poverty, 
                        "<br>Incident Rate: ", incident_rate_by_year_nta)) |> 
    layout(title = "Percent Below the Poverty Line and Incident Rate in Queens",
           xaxis = list(title = 'Percentage of People Whose Income is Below the Poverty Line'),
           yaxis = list(title = 'Incident Rate'),
           legend = list(title = list(text = 'Neighborhood')))

Corona and East Elmhurst show relatively high incident rates, particularly compared to neighborhoods with similar poverty percentages.

Staten Island

# Scatter plot for Staten Island
data_clean |> 
  filter(neighbourhood_group == "Staten Island") |> 
  plot_ly(data = _, x = ~Percent_poverty, y = ~incident_rate_by_year_nta, 
          color = ~NTA,
          colors = "inferno", 
          type = "scatter",
          mode = "markers",
          text = ~paste("Neighborhood: ", NTA, "<br>Borough: ", neighbourhood_group, 
                        "<br>% Below Poverty Line: ", Percent_poverty, 
                        "<br>Incident Rate: ", incident_rate_by_year_nta)) |> 
    layout(title = "Percent Below the Poverty Line and Incident Rate in Staten Island",
           xaxis = list(title = 'Percentage of People Whose Income is Below the Poverty Line'),
           yaxis = list(title = 'Incident Rate'),
           legend = list(title = list(text = 'Neighborhood')))

In Staten Island, the relationship between poverty and incident rates is less pronounced compared to other boroughs.

# Load necessary libraries
library(dplyr)
library(plotly)

# 1. Load your incidents data
incidents_data <- read.csv("data_final.csv")

# 2. Filter data from 2017 to 2023
incidents_filtered <- incidents_data %>%
  filter(Year >= 2017 & Year <= 2023)

# 3. Aggregate total incidents by CDTA
incidents_by_cdta <- incidents_filtered %>%
  group_by(CDTA) %>%
  summarise(
    total_incidents = n(),
    Longitude = mean(Longitude, na.rm = TRUE),
    Latitude = mean(Latitude, na.rm = TRUE)
  ) %>%
  ungroup()

# 4. Define initial breaks from 0 to 400 with intervals of 5
initial_breaks <- seq(0, 400, by = 5)

# 5. Calculate the maximum number of incidents
max_incidents <- max(incidents_by_cdta$total_incidents, na.rm = TRUE)

# 6. Check if maximum incidents exceed 400 and adjust breaks and labels accordingly
if (max_incidents > 400) {
  # Extend breaks to include all incidents > 400
  extended_breaks <- c(initial_breaks, Inf)
  
  # Create labels for all intervals, including the last one for incidents >400
  labels <- c(
    paste(initial_breaks[-length(initial_breaks)], initial_breaks[-1], sep = "-"),
    paste0("401+", max_incidents)
  )
} else {
  # No need to extend breaks
  extended_breaks <- initial_breaks
  labels <- paste(initial_breaks[-length(initial_breaks)], initial_breaks[-1], sep = "-")
}

# 7. Validate that the number of labels matches the number of intervals
num_intervals <- length(extended_breaks) - 1
num_labels <- length(labels)

if (num_intervals != num_labels) {
  stop("Number of labels does not match the number of intervals.")
}

# 8. Assign incident ranges
incidents_by_cdta <- incidents_by_cdta %>%
  mutate(
    incident_range = cut(
      total_incidents,
      breaks = extended_breaks,
      include.lowest = TRUE,
      right = FALSE,  # Left-inclusive intervals [a, b)
      labels = labels
    )
  )

# 9. Verify the distribution of incident ranges
print(table(incidents_by_cdta$incident_range, useNA = "ifany"))
## 
##     0-5    5-10   10-15   15-20   20-25   25-30   30-35   35-40   40-45   45-50 
##       6       5       3       2       4       0       0       3       1       2 
##   50-55   55-60   60-65   65-70   70-75   75-80   80-85   85-90   90-95  95-100 
##       1       2       1       1       2       0       0       2       1       0 
## 100-105 105-110 110-115 115-120 120-125 125-130 130-135 135-140 140-145 145-150 
##       0       0       1       1       1       0       1       2       2       0 
## 150-155 155-160 160-165 165-170 170-175 175-180 180-185 185-190 190-195 195-200 
##       0       0       1       0       2       0       0       0       1       1 
## 200-205 205-210 210-215 215-220 220-225 225-230 230-235 235-240 240-245 245-250 
##       0       0       0       0       2       0       0       0       0       0 
## 250-255 255-260 260-265 265-270 270-275 275-280 280-285 285-290 290-295 295-300 
##       2       0       1       1       0       0       0       0       0       0 
## 300-305 305-310 310-315 315-320 320-325 325-330 330-335 335-340 340-345 345-350 
##       0       0       0       0       1       1       0       0       0       0 
## 350-355 355-360 360-365 365-370 370-375 375-380 380-385 385-390 390-395 395-400 
##       0       2       0       1       0       1       1       1       0       0 
## 401+551 
##       5
# 10. Check for missing coordinates and exclude them
missing_coords <- incidents_by_cdta %>%
  filter(is.na(Longitude) | is.na(Latitude))

if (nrow(missing_coords) > 0) {
  cat("Warning: The following CDTAs have missing coordinates and will be excluded from the plot:\n")
  print(missing_coords$CDTA)
  
  # Exclude CDTAs with missing coordinates
  incidents_by_cdta <- incidents_by_cdta %>%
    filter(!is.na(Longitude) & !is.na(Latitude))
}

# 11. Set your Mapbox access token
Sys.setenv('MAPBOX_TOKEN' = 'your_mapbox_access_token')  # Replace with your actual token

# 12. Create the scatter map
incident_map <- plot_ly(
  data = incidents_by_cdta,
  type = "scattermapbox",
  mode = "markers",
  lon = ~Longitude,  # Use exact column name with correct case
  lat = ~Latitude,   # Use exact column name with correct case
  color = ~incident_range,
  colors = "viridis",  # Use lowercase if necessary
  marker = list(
    size = 8,
    opacity = 0.7
  ),
  text = ~paste(
    "CDTA: ", CDTA,
    "<br>Total Incidents: ", total_incidents,
    "<br>Incident Range: ", incident_range
  )
) %>%
  layout(
    title = "Total Number of Incidents Across NYC CDTAs (2017-2023)",
    mapbox = list(
      style = "carto-positron",  # Choose desired map style
      center = list(lon = -74.0060, lat = 40.7128),  # Centered on NYC
      zoom = 10
    ),
    legend = list(title = list(text = 'Incident Range'))
  )

# 13. Display the map
incident_map
# Load necessary libraries
library(dplyr)
library(tidyr)
library(plotly)

# 1. Load your incidents data
incidents_data <- read.csv("data_final.csv")

# 2. Filter data from 2017 to 2023 and remove rows with missing values in key columns
incidents_filtered <- incidents_data %>%
  filter(Year >= 2017 & Year <= 2023) %>%
  drop_na(Sky_Is_Dark, Longitude, Latitude, NTA, OCCUR_TIME)  # Ensure essential columns have no NA


# Optional: Relabel Sky_Is_Dark for better readability
incidents_filtered <- incidents_filtered %>%
  mutate(Sky_Condition = ifelse(Sky_Is_Dark, "Night", "Day"))

# 3. Set your Mapbox access token
Sys.setenv('MAPBOX_TOKEN' = 'your_mapbox_access_token')  # Replace with your actual token

# 4. Create the interactive map using the filtered data
plot_ly(data = incidents_filtered, 
        type = "scattermapbox",       # Specifies that we're creating a Mapbox scatter plot
        mode = "markers",             # Use markers to represent data points
        lon = ~Longitude,             # Longitude for x-axis (map)
        lat = ~Latitude,              # Latitude for y-axis (map)
        color = ~Sky_Condition,       # Color markers based on Sky_Condition
        colors = c("Day" = "orange", "Night" = "blue"), # Assign specific colors
        marker = list(size = 5,        # Set marker size
                      opacity = 0.7),  # Set marker opacity for better visibility
        text = ~paste("NTA:", NTA,
                      "<br>Time of Incident:", OCCUR_TIME,
                      "<br>Sky Condition:", Sky_Condition)  # Hover text
) |> 
  layout(
    title = "DAY OR NIGHT Incidents in NYC",  # Set the plot title
    mapbox = list(
      style = "carto-positron",      # Map style
      center = list(lon = -73.94, lat = 40.84),  # Center the map on NYC
      zoom = 12                      # Set zoom level
    ),
    showlegend = TRUE,               # Display the legend
    legend = list(title = list(text = 'Sky Condition'))  # Legend title
  )